#include <stdio.h>

struct ListNode {
    int val;
    struct ListNode* next;
};

struct ListNode* removeElements(struct ListNode* head, int val)
{
    if (head == NULL)
        return head;
    while (head && head->val == val)
    {
        struct ListNode* next = head->next;
        free(head);
        head = next;
    }
    if (head == NULL)
        return head;
    struct ListNode* pur = head;
    struct ListNode* prv = NULL;
    while (pur)
    {
        if (pur->val == val)
        {
            prv->next = pur->next;
            free(pur);
            pur = prv->next;
        }
        else
        {
            prv = pur;
            pur = pur->next;
        }
    }
    return head;
}